package com.hethongviet.job.pages;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

import com.hethongviet.job.AppMain;
import com.hethongviet.job.Config;
import com.hethongviet.job.Connectivity;
import com.hethongviet.job.R;
import com.hethongviet.job.helpers.CodeResult;
import com.hethongviet.job.helpers.ComparableHelper;
import com.hethongviet.job.helpers.ServiceHelper;
import com.hethongviet.job.helpers.ComparableHelper.ProjectCompartorByDateCreateDown;
import com.hethongviet.job.helpers.ComparableHelper.ProjectCompartorByDateCreateUp;
import com.hethongviet.job.helpers.ComparableHelper.ProjectCompartorByNameDown;
import com.hethongviet.job.helpers.ComparableHelper.ProjectCompartorByNameUp;
import com.hethongviet.job.helpers.ComparableHelper.ProjectCompartorByWorkerDown;
import com.hethongviet.job.helpers.ComparableHelper.ProjectCompartorByWorkerUp;
import com.hethongviet.job.helpers.ComparableHelper.TaskCompartorByCodeDown;
import com.hethongviet.job.helpers.ComparableHelper.TaskCompartorByCodeUp;
import com.hethongviet.job.helpers.ComparableHelper.TaskCompartorByDateRequireFinishDown;
import com.hethongviet.job.helpers.ComparableHelper.TaskCompartorByDateRequireFinishUp;
import com.hethongviet.job.helpers.ComparableHelper.TaskCompartorByDateRequireStartDown;
import com.hethongviet.job.helpers.ComparableHelper.TaskCompartorByDateRequireStartUp;
import com.hethongviet.job.helpers.ComparableHelper.TaskCompartorByNameDown;
import com.hethongviet.job.helpers.ComparableHelper.TaskCompartorByNameUp;
import com.hethongviet.job.helpers.TabMenu;
import com.hethongviet.job.helpers.database.CommentSQLite;
import com.hethongviet.job.helpers.database.TaskSQLite;
import com.hethongviet.job.helpers.listadapter.ListItemProjectAdapter;
import com.hethongviet.job.helpers.listadapter.ListItemTaskAdapter;
import com.hethongviet.job.models.Comment;
import com.hethongviet.job.models.FileGeneral;
import com.hethongviet.job.models.FileImage;
import com.hethongviet.job.models.Tab;
import com.hethongviet.job.models.Task;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

@TargetApi(5)
public class MainActivity extends Activity
{

	private ListView _listViewProjects = null;
	private ListView _listViewTasks = null;
	private ListItemProjectAdapter _listViewProjectsAdapter = null;
	private ListItemTaskAdapter _listViewTasksAdapter = null;

	private LinearLayout _linearLayoutProjects = null;
	private LinearLayout _linearLayoutTasks = null;
	private TabMenu _tabMenu = null;

	private Button _buttonTabProject = null;
	// private BadgeView _badgeViewProject = null;
	private Button _buttonTabTask = null;
	// private BadgeView _badgeViewTask = null;
	private Button _buttonTabTaskDelay = null;
	// private BadgeView _badgeViewTaskDelay = null;

	private TextView _textTotalProjects = null;
	private TextView _textTotalTasks = null;
	private TextView _textProjectName = null;

	private boolean _isSynchrozing = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		AppMain.prepareWindow(this);
		setContentView(R.layout.page_main);

		_buttonTabProject = (Button) findViewById(R.id.buttonTabProject);
		_buttonTabTask = (Button) findViewById(R.id.buttonTabTask);
		_buttonTabTaskDelay = (Button) findViewById(R.id.buttonTabTaskDelay);

		_listViewProjects = (ListView) findViewById(R.id.listViewProjects);
		_listViewTasks = (ListView) findViewById(R.id.listViewTasks);

		_linearLayoutProjects = (LinearLayout) findViewById(R.id.layoutListProjects);
		_linearLayoutTasks = (LinearLayout) findViewById(R.id.layoutListTasks);

		_textTotalProjects = (TextView) findViewById(R.id.textTotalProjects);
		_textTotalTasks = (TextView) findViewById(R.id.textTotalTasks);
		_textProjectName = (TextView) findViewById(R.id.textProjectName);

		/* Process for tab menu */
		Tab[] tabs = new Tab[AppMain.TOTAL_TAB_MAIN_PAGE];

		tabs[AppMain.TAB_PROJECT] = new Tab();
		tabs[AppMain.TAB_PROJECT].setButton(_buttonTabProject);
		tabs[AppMain.TAB_PROJECT].setLinearLayout(_linearLayoutProjects);
		// _badgeViewProject = new BadgeView(this, _buttonTabProject);
		// _badgeViewProject.setBackgroundResource(R.drawable.badge_ifaux);
		// _badgeViewProject.setTextSize(16);

		tabs[AppMain.TAB_TASK] = new Tab();
		tabs[AppMain.TAB_TASK].setButton(_buttonTabTask);
		tabs[AppMain.TAB_TASK].setImplementEventAfter(true);
		tabs[AppMain.TAB_TASK].setLinearLayout(_linearLayoutTasks);
		_buttonTabTask.setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				AppMain._listTasksShow.clear();
				for (Task task : AppMain._listTasksAll)
				{
					AppMain._listTasksShow.add(task);
				}

				_textProjectName.setVisibility(View.GONE);
				_tabMenu.moveToTab(AppMain.TAB_TASK);
				refreshListTasks(false);
			}
		});

		_buttonTabTaskDelay.setText(String.format(
				getString(R.string.textTaskDelay),
				AppMain.getNumberTasksDelay()));

		tabs[AppMain.TAB_TASK_DELAY] = new Tab();
		tabs[AppMain.TAB_TASK_DELAY].setButton(_buttonTabTaskDelay);
		tabs[AppMain.TAB_TASK_DELAY].setImplementEventAfter(true);
		tabs[AppMain.TAB_TASK_DELAY].setLinearLayout(_linearLayoutTasks);

		// _badgeViewTaskDelay = new BadgeView(this, _buttonTabTaskDelay);
		// _badgeViewTaskDelay.setLayoutParams(new
		// LayoutParams(android.widget.FrameLayout.LayoutParams.WRAP_CONTENT,
		// android.widget.FrameLayout.LayoutParams.WRAP_CONTENT));
		// _badgeViewTaskDelay.setBackgroundResource(R.drawable.bagview_red_nine);
		// _badgeViewTaskDelay.setTextSize(9);
		// _badgeViewTaskDelay.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
		// _badgeViewTaskDelay.setBadgeMargin(2, 40);
		// _badgeViewTaskDelay.setPadding(0, 0, 5, 0);
		// _badgeViewTaskDelay.setText("" + AppMain.getNumberTasksDelay());

		// _badgeViewTaskDelay.show();
		_buttonTabTaskDelay.setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				AppMain._listTasksShow.clear();
				AppMain.getTasksDelay();
				_tabMenu.moveToTab(AppMain.TAB_TASK_DELAY);
				refreshListTasks(false);
				_textProjectName.setVisibility(View.GONE);
			}
		});

		_tabMenu = new TabMenu(tabs, R.drawable.button_tab2,
				R.drawable.button_tab2_highlight);

		/* List of projects */
		_textTotalProjects.setText(AppMain._listProjects.size() + " "
				+ getString(R.string.textProjectLowerCase));
		// _badgeViewProject.setText(AppMain._listProjects.size() + "");
		// _badgeViewProject.show();

		_listViewProjectsAdapter = new ListItemProjectAdapter(
				MainActivity.this, AppMain._listProjectsShow);
		_listViewProjects.setAdapter(_listViewProjectsAdapter);
		_listViewProjects.setTextFilterEnabled(true);
		_listViewProjects.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				AppMain._currentIndexProject = position;
				String currentProjectId = AppMain.getCurrentProject().getId();
				AppMain.getTasks(currentProjectId);
				_textProjectName.setText(getString(R.string.textTaskProjectName)
						+ " " + AppMain.getCurrentProject().getName());
				_textProjectName.setVisibility(View.VISIBLE);
				_tabMenu.moveToTab(AppMain.TAB_TASK);
				refreshListTasks(false);
			}
		});

		/* Initiate List of tasks */
		_listViewTasksAdapter = new ListItemTaskAdapter(MainActivity.this,
				AppMain._listTasksShow);
		_listViewTasks.setAdapter(_listViewTasksAdapter);
		_listViewTasks.setTextFilterEnabled(true);
		_listViewTasks.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				AppMain._currentIndexTask = position;
				if (!Config.USE_DATABASE)
				{
					AppMain.showProgress(MainActivity.this);
					new Thread(new Runnable()
					{
						public void run()
						{
							AppMain._codeResultService = AppMain.doGetCommentsByTask(
									MainActivity.this,
									AppMain.getCurrentTask().getId());
							AppMain.hideProgressDialog();
						}
					}).start();
				}
				else
				{
					CommentSQLite commentSQLite = new CommentSQLite(
							MainActivity.this);

					AppMain._listComments = commentSQLite.getAllByTask(AppMain.getCurrentTask().getId());

					AppMain.debug("" + AppMain._listComments.size());
					if (!AppMain._isSMSEnable
							&& AppMain._listComments.size() == 0)
					{
						AppMain.showProgress(MainActivity.this);
						new Thread(new Runnable()
						{
							public void run()
							{
								AppMain._codeResultService = AppMain.doGetCommentsByTask(
										MainActivity.this,
										AppMain.getCurrentTask().getId());
								AppMain.hideProgressDialog();
							}
						}).start();
					}
					else
					{
						Intent intent = new Intent(MainActivity.this,
								DetailTaskActivity.class);
						startActivity(intent);
					}
				}
			}
		});

//		new Thread(new Runnable()
//		{
//
//			@Override
//			public void run()
//			{
//				synchronizeGPRS();
//			}
//		}).start();
	}

	/*
	 * Update the remain data when sent data through the GPRS, or low network
	 */
	private void synchronizeGPRS()
	{
		if (_isSynchrozing)
		{
			return;
		}

		_isSynchrozing = true;

		if (Config.USE_DATABASE)
		{
			TaskSQLite taskSQLite = new TaskSQLite(MainActivity.this);

			/* Sync the data */
			if (Connectivity.isConnectedFast(MainActivity.this))
			{
				AppMain.debug("Sync data !!!!!!!!!!!!!!!!!!!");

				/* Synchronize the tasks */
				List<Task> tasks = taskSQLite.getAll();

				for (Task task : tasks)
				{

					FileImage imageFile = null;
					String resultString = "";

					if (!task.isSyncDataStart())
					{
						AppMain.debug("Sync task " + task.getCode());

						imageFile = task.getImageFileStart();
						if (imageFile != null
								&& !TextUtils.isEmpty(imageFile.getName()))
						{
							String imageData = AppMain.getStringImageData(
									imageFile, false);
							if (!imageData.equals(ServiceHelper.ERROR_OUT_OF_MEMORY))
							{
								AppMain.debug("ServiceHelper.doSyncStartTask( imageFile.getName() = "
										+ imageFile.getName()
										+ ", imageDataYes = "
										+ !TextUtils.isEmpty(imageData)
										+ ", "
										+ " AppMain.getCurrentTask().getId() = "
										+ AppMain.getCurrentTask().getId()
										+ ")");

								resultString = ServiceHelper.doSyncStartTask(
										imageFile.getName(), imageData,
										AppMain.getCurrentTask().getId());

								if (resultString.equalsIgnoreCase("ok"))
								{
									task.setSyncDataStart(true);
									taskSQLite.insert(task);

									File imageFileStorage = new File(
											imageFile.getPath() + "/"
													+ imageFile.getName());
									if (imageFileStorage.exists())
									{
										imageFileStorage.delete();
									}
								}
								else
								{
									AppMain.debug("Fail Synchronize! message = "
											+ resultString);
								}
							}
							else
							{
								AppMain.debug("Error Synchronize! Out of memory of task id = "
										+ AppMain.getCurrentTask().getId());
								System.gc();
							}
						}
					}

					if (!task.isSyncDataFinish())
					{
						AppMain.debug("Sync!!!!!!!!!!");
						imageFile = task.getImageFileFinish();
						if (imageFile != null
								&& !TextUtils.isEmpty(imageFile.getName()))
						{
							String imageData = AppMain.getStringImageData(
									imageFile, false);
							if (!imageData.equals(ServiceHelper.ERROR_OUT_OF_MEMORY))
							{
								AppMain.debug("ServiceHelper.doSyncFinishTask( imageFile.getName() = "
										+ imageFile.getName()
										+ ", imageDataYes = "
										+ !TextUtils.isEmpty(imageData)
										+ ", "
										+ " AppMain.getCurrentTask().getId() = "
										+ AppMain.getCurrentTask().getId()
										+ ")");

								resultString = ServiceHelper.doSyncFinishTask(
										imageFile.getName(), imageData,
										AppMain.getCurrentTask().getId());

								if (resultString.equalsIgnoreCase("ok"))
								{

									File imageFileStorage = new File(
											imageFile.getPath() + "/"
													+ imageFile.getName());
									if (imageFileStorage.exists())
									{
										imageFileStorage.delete();
									}

									task.setSyncDataFinish(true);
									taskSQLite.insert(task);
								}
								else
								{
									AppMain.debug("Fail Synchronize! message = "
											+ resultString);
								}
							}
							else
							{
								AppMain.debug("Error Synchronize! Out of memory of task id = "
										+ AppMain.getCurrentTask().getId());
								System.gc();
							}
						}
					}
				}

				/* Synchronize the comments */
				CommentSQLite commentSQLite = new CommentSQLite(
						MainActivity.this);

				List<Comment> comments = commentSQLite.getAll();

				for (Comment comment : comments)
				{
					if (!comment.isSyncData())
					{
						AppMain.debug("Sync Comment = " + comment.getContent());
						FileImage imageFile = comment.getFileImage();
						FileGeneral audioFileGeneral = comment.getFileAudio();
						FileGeneral attachFileGeneral = comment.getFileAttachment();

						if (imageFile != null
								&& !TextUtils.isEmpty(imageFile.getPath())
								&& !TextUtils.isEmpty(imageFile.getName())
								|| audioFileGeneral != null
								&& !TextUtils.isEmpty(audioFileGeneral.getPath())
								&& !TextUtils.isEmpty(audioFileGeneral.getName())
								|| attachFileGeneral != null
								&& !TextUtils.isEmpty(attachFileGeneral.getPath())
								&& !TextUtils.isEmpty(attachFileGeneral.getName()))
						{
							String imageData = null;
							String attachData = null;
							String audioData = null;

							AppMain.debug("@@@@@@@@@@@@@@@@ imageFile.getPath() = "
									+ imageFile.getPath());
							AppMain.debug("@@@@@@@@@@@@@@@@ imageFile.getName() = "
									+ imageFile.getName());
							AppMain.debug("@@@@@@@@@@@@@@@@ audioFile.getPath() = "
									+ audioFileGeneral.getPath());
							AppMain.debug("@@@@@@@@@@@@@@@@ audioFile.getName() = "
									+ audioFileGeneral.getName());
							AppMain.debug("@@@@@@@@@@@@@@@@ attachFile.getPath() = "
									+ attachFileGeneral.getPath());
							AppMain.debug("@@@@@@@@@@@@@@@@ attachFile.getName() = "
									+ attachFileGeneral.getName());

							/* Rename the image name */
							if (imageFile != null
									&& !TextUtils.isEmpty(imageFile.getName()))
							{
								imageData = AppMain.getStringImageData(
										imageFile, false);
								if (TextUtils.isEmpty(imageData))
								{
									imageFile.setName("");
									AppMain.debug("data image can not load!!!!");
								}
								else
								{
									AppMain.debug("data image loaded!!!!");
								}
							}
							else
							{
								imageFile = new FileImage(null, "", "", "");
								AppMain.debug("data imageFile can not load!!!!");

							}

							if (attachFileGeneral != null
									&& !TextUtils.isEmpty(attachFileGeneral.getName()))
							{
								attachData = AppMain.getStringFileData(
										attachFileGeneral, false);

								if (TextUtils.isEmpty(attachData))
								{
									attachFileGeneral.setName("");
									AppMain.debug("data attachFile can not load!!!!");
								}
								else
								{
									AppMain.debug("data attach loaded!!!!");
								}
							}
							else
							{
								attachFileGeneral = new FileGeneral("", "", "");
							}

							if (Config.USE_AUDIO_RECORD)
							{
								audioData = AppMain.getStringFileData(
										audioFileGeneral, false);
								if (TextUtils.isEmpty(audioData))
								{
									audioFileGeneral.setName("");
									AppMain.debug("data audio can not load!!!!");
								}
								else
								{
									AppMain.debug("data audio loaded!!!!");
								}
							}
							else
							{
								AppMain.debug("No record audio!");
							}

							AppMain.debug("ServiceHelper.doSyncAddComment(AppMain.getCurrentTask().getId() = "
									+ comment.getId()
									+ ", imageName = "
									+ imageFile.getName()
									+ ", imageDataYes = "
									+ !TextUtils.isEmpty(imageData)
									+ ", attachStringName = "
									+ attachFileGeneral.getName()
									+ ", attachData = "
									+ !TextUtils.isEmpty(attachData)
									+ " audioStringName = "
									+ audioFileGeneral.getName()
									+ ", audio data  = "
									+ !TextUtils.isEmpty(audioData) + ")");

							String resultString = ServiceHelper.doSyncAddComment(
									comment.getId(), imageFile.getName(),
									imageData, attachFileGeneral.getName(),
									attachData, audioFileGeneral.getName(),
									audioData);

							if (resultString.equalsIgnoreCase("ok"))
							{
								File imageFileStorage = new File(
										imageFile.getPath() + "/"
												+ imageFile.getName());
								File attachFileStorage = new File(
										attachFileGeneral.getPath() + "/"
												+ attachFileGeneral.getName());
								File audioFileStorage = new File(
										audioFileGeneral.getPath() + "/"
												+ audioFileGeneral.getName());

								if (imageFileStorage.exists())
								{
									imageFileStorage.delete();
								}
								if (attachFileStorage.exists())
								{
									attachFileStorage.delete();
								}
								if (audioFileStorage.exists())
								{
									audioFileStorage.delete();
								}

								comment.setSyncData(true);

								commentSQLite.insert(comment);
							}
							else
							{
								AppMain.debug("Fail Synchronize! message = "
										+ resultString);
							}
						}

					}
				}

			}
		}

		_isSynchrozing = false;
	}

	private int getTotalTaskDelay()
	{
		int countTaskDelay = 0;
		for (Task task : AppMain._listTasksShow)
		{
			if (task.isDelay())
				countTaskDelay++;
		}
		return countTaskDelay;
	}

	private int getTotalTaskDelayStart()
	{
		int countTaskDelay = 0;
		for (Task task : AppMain._listTasksShow)
		{
			if (task.getStatus() == Task.STATUS_DELAY_START)
				countTaskDelay++;
		}
		return countTaskDelay;
	}

	private Spanned getTaskTotalString(boolean isFitering)
	{
		int numberTaskDelay = getTotalTaskDelay();
		int numberTaskDelayStart = getTotalTaskDelayStart();
		String totalTasks = AppMain._listTasksShow.size() + " "
				+ getString(R.string.textTaskLowerCaseAll);
		String totalTasksDelayStart = getString(R.string.textTaskStatusDelayStart)
				+ ": " + numberTaskDelayStart;
		String totalTasksDelayFinish = getString(R.string.textTaskStatusDelayFinish)
				+ ": " + (numberTaskDelay - numberTaskDelayStart);

		if (isFitering) /* Filtering */
		{
			return Html.fromHtml(totalTasks);
		}
		else
			return Html.fromHtml(totalTasks + " (<font color="
					+ Task.getStatusColor(this, Task.STATUS_DELAY_START) + ">"
					+ totalTasksDelayStart + "</font>" + ", " + "<font color="
					+ Task.getStatusColor(this, Task.STATUS_DELAY_FINISH) + ">"
					+ totalTasksDelayFinish + "</font>)");
	}

	private Spanned getTaskDelayTotalString()
	{
		int numberTaskDelay = getTotalTaskDelay();
		int numberTaskDelayStart = getTotalTaskDelayStart();
		return Html.fromHtml("<font color="
				+ Task.getStatusColor(this, Task.STATUS_DELAY_START) + ">"
				+ getString(R.string.textTaskStatusDelayStart) + ": "
				+ numberTaskDelayStart + "</font>" + ", " + "<font color="
				+ Task.getStatusColor(this, Task.STATUS_DELAY_FINISH) + ">"
				+ getString(R.string.textTaskStatusDelayFinish) + ": "
				+ (numberTaskDelay - numberTaskDelayStart) + "</font>");
	}

	public void processDialogListSortingProjects(int itemIndex)
	{
		if (AppMain._listProjects.size() < 2)
			return;
		switch (itemIndex)
		{
		case AppMain.SORT_PROJECT_DATE_CREATE_DOWN:
			ComparableHelper.ProjectCompartorByDateCreateDown projectCompartorByDateCreateDown = new ProjectCompartorByDateCreateDown();
			Collections.sort(AppMain._listProjectsShow,
					projectCompartorByDateCreateDown);
			break;
		case AppMain.SORT_PROJECT_DATE_CREATE_UP:
			ComparableHelper.ProjectCompartorByDateCreateUp projectCompartorByDateCreateUp = new ProjectCompartorByDateCreateUp();
			Collections.sort(AppMain._listProjectsShow,
					projectCompartorByDateCreateUp);
			break;
		case AppMain.SORT_PROJECT_NAME_AZ:
			ProjectCompartorByNameUp projectCompartorByNameUp = new ProjectCompartorByNameUp();
			Collections.sort(AppMain._listProjectsShow,
					projectCompartorByNameUp);
			break;
		case AppMain.SORT_PROJECT_NAME_ZA:
			ProjectCompartorByNameDown projectCompartorByNameDown = new ProjectCompartorByNameDown();
			Collections.sort(AppMain._listProjectsShow,
					projectCompartorByNameDown);
			break;
		case AppMain.SORT_PROJECT_WORKER_NAME_AZ:
			ComparableHelper.ProjectCompartorByWorkerUp projectCompartorByWorkerUp = new ProjectCompartorByWorkerUp();
			Collections.sort(AppMain._listProjectsShow,
					projectCompartorByWorkerUp);
			break;
		case AppMain.SORT_PROJECT_WORKER_NAME_ZA:
			ComparableHelper.ProjectCompartorByWorkerDown projectCompartorByWorkerDown = new ProjectCompartorByWorkerDown();
			Collections.sort(AppMain._listProjectsShow,
					projectCompartorByWorkerDown);
			break;

		default:
			break;
		}
		refreshListProjects();
	}

	public void processDialogListFilteringTasks(int itemIndex)
	{
		if (_textProjectName.getVisibility() != View.VISIBLE)
		{
			AppMain.getTasksAll();
		}
		else
		{
			String currentProjectId = AppMain.getCurrentProject().getId();
			AppMain.getTasks(currentProjectId);
		}

		if (itemIndex != AppMain.FILTER_TASK_ALL)
		{
			List<Task> tempTasks = new Vector<Task>();
			for (Task task : AppMain._listTasksShow)
			{
				tempTasks.add(task);
			}
			AppMain._listTasksShow.clear();
			switch (itemIndex)
			{
			case AppMain.FILTER_TASK_DELAY_FINISH:
				for (Task task : tempTasks)
				{
					if (task.getStatus() == Task.STATUS_DELAY_FINISH)
						AppMain._listTasksShow.add(task);
				}
				break;
			case AppMain.FILTER_TASK_DELAY_START:
				for (Task task : tempTasks)
				{
					if (task.getStatus() == Task.STATUS_DELAY_START)
						AppMain._listTasksShow.add(task);
				}
				break;
			case AppMain.FILTER_TASK_FINISH:
				for (Task task : tempTasks)
				{
					if (task.getStatus() == Task.STATUS_FINISH)
						AppMain._listTasksShow.add(task);
				}
				break;
			case AppMain.FILTER_TASK_IN_PROGRESS:
				for (Task task : tempTasks)
				{
					if (task.getStatus() == Task.STATUS_IN_PROCESS
							|| task.getStatus() == Task.STATUS_DELAY_FINISH)
						AppMain._listTasksShow.add(task);
				}
				break;
			case AppMain.FILTER_TASK_JUST_CREATE:
				for (Task task : tempTasks)
				{
					if (task.getStatus() == Task.STATUS_JUST_CREATE
							|| task.getStatus() == Task.STATUS_DELAY_START)
						AppMain._listTasksShow.add(task);
				}
				break;

			default:
				break;
			}
			refreshListTasks(true);
		}
		else
			refreshListTasks(false);
	}

	public void processDialogListFilteringTasksDelay(int itemIndex)
	{
		AppMain.getTasksDelay();
		// List<Task> tempTasks = AppMain._listTasksShow;
		List<Task> tempTasks = new Vector<Task>();
		for (Task task : AppMain._listTasksShow)
		{
			tempTasks.add(task);
		}
		if (itemIndex != AppMain.FILTER_TASK_DELAY_ALL)
		{
			AppMain._listTasksShow.clear();
			switch (itemIndex)
			{
			case AppMain.FILTER_TASK_DELAY_DELAY_FINISH:
				for (Task task : tempTasks)
				{
					if (task.getStatus() == Task.STATUS_DELAY_FINISH)
						AppMain._listTasksShow.add(task);
				}
				break;
			case AppMain.FILTER_TASK_DELAY_DELAY_START:
				for (Task task : tempTasks)
				{
					if (task.getStatus() == Task.STATUS_DELAY_START)
						AppMain._listTasksShow.add(task);
				}
				break;

			default:
				break;
			}
			refreshListTasks(true);
		}
		else
			refreshListTasks(false);
	}

	private void showProgressBar()
	{
		AppMain.showProgress(this);
		enableAllClick(false);
	}

	private void enableAllClick(boolean enable)
	{
		_buttonTabProject.setClickable(enable);
		_buttonTabTask.setClickable(enable);
		_buttonTabTaskDelay.setClickable(enable);
		_listViewProjects.setClickable(enable);
		_listViewTasks.setClickable(enable);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		AppMain.debug("Window focus change!");
		if (AppMain._isDoneLoading)
		{
			AppMain.debug("Window focus change! isdonedownloading result "
					+ AppMain._codeResultService);
			AppMain.debug("Window focus change! isdonedownloading CodeResult.SUCCESS_GET_TASKS = "
					+ CodeResult.SUCCESS_GET_TASKS);
			switch (AppMain._codeResultService)
			{
			case ERROR_NETWORK:
				AppMain.showAlert(this, R.string.textErrorNetwork, false);
				break;
			case SUCCESS_GET_PROJECTS:
				refreshListProjects();
				break;
			case SUCCESS_GET_COMMENTS:
				AppMain._codeResultService = CodeResult.NONE;
				AppMain._isDoneLoading = false;
				enableAllClick(true);
				Intent intent = new Intent(MainActivity.this,
						DetailTaskActivity.class);
				startActivity(intent);
				break;
			case SUCCESS_GET_TASKS:
				if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK)
				{
					refreshListTasks(false);
					/* Move to tab task */
					_tabMenu.moveToTab(1);
				}
				else
				// tab delay
				{
					refreshListTasks(false);
					/* Move to tab task */
					_tabMenu.moveToTab(2);
				}

				AppMain.debug("Window focus change! change tab! task");
				break;
			default:
				break;
			}
			AppMain._codeResultService = CodeResult.NONE;
			AppMain._isDoneLoading = false;
			enableAllClick(true);
		}
		super.onWindowFocusChanged(hasFocus);
	}

	public void processDialogListSortingTasks(int itemIndex)
	{
		if (AppMain._listTasksShow.size() < 2)
			return;
		switch (itemIndex)
		{
		case AppMain.SORT_TASK_CODE_AZ:
			TaskCompartorByCodeUp taskCompartorByCodeUp = new TaskCompartorByCodeUp();
			Collections.sort(AppMain._listTasksShow, taskCompartorByCodeUp);
			break;
		case AppMain.SORT_TASK_CODE_ZA:
			TaskCompartorByCodeDown taskCompartorByCodeDown = new TaskCompartorByCodeDown();
			Collections.sort(AppMain._listTasksShow, taskCompartorByCodeDown);
			break;
		// case AppMain.SORT_TASK_DATE_ACTUAL_FINISH_DOWN:
		// TaskCompartorByDateActualFinishDown
		// taskCompartorByDateActualFinishDown = new
		// TaskCompartorByDateActualFinishDown();
		// Collections.sort(AppMain._tasksListShow,
		// taskCompartorByDateActualFinishDown);
		// break;
		// case AppMain.SORT_TASK_DATE_ACTUAL_FINISH_UP:
		// TaskCompartorByDateActualFinishUp
		// taskCompartorByDateActualFinishUp= new
		// TaskCompartorByDateActualFinishUp();
		// Collections.sort(AppMain._tasksListShow,
		// taskCompartorByDateActualFinishUp);
		// break;
		// case AppMain.SORT_TASK_DATE_ACTUAL_START_DOWN:
		// TaskCompartorByDateActualStartDown
		// taskCompartorByDateActualStartDown= new
		// TaskCompartorByDateActualStartDown();
		// Collections.sort(AppMain._tasksListShow,
		// taskCompartorByDateActualStartDown);
		// break;
		// case AppMain.SORT_TASK_DATE_ACTUAL_START_UP:
		// TaskCompartorByDateActualStartUp
		// taskCompartorByDateActualStartUp= new
		// TaskCompartorByDateActualStartUp();
		// Collections.sort(AppMain._tasksListShow,
		// taskCompartorByDateActualStartUp);
		// break;
		case AppMain.SORT_TASK_DATE_REQUIRE_FINISH_DOWN:
			TaskCompartorByDateRequireFinishDown taskCompartorByDateRequireFinishDown = new TaskCompartorByDateRequireFinishDown();
			Collections.sort(AppMain._listTasksShow,
					taskCompartorByDateRequireFinishDown);
			break;
		case AppMain.SORT_TASK_DATE_REQUIRE_FINISH_UP:
			TaskCompartorByDateRequireFinishUp taskCompartorByDateRequireFinishUp = new TaskCompartorByDateRequireFinishUp();
			Collections.sort(AppMain._listTasksShow,
					taskCompartorByDateRequireFinishUp);
			break;
		case AppMain.SORT_TASK_DATE_REQUIRE_START_DOWN:
			TaskCompartorByDateRequireStartDown taskCompartorByDateRequireStartDown = new TaskCompartorByDateRequireStartDown();
			Collections.sort(AppMain._listTasksShow,
					taskCompartorByDateRequireStartDown);
			break;
		case AppMain.SORT_TASK_DATE_REQUIRE_START_UP:
			TaskCompartorByDateRequireStartUp taskCompartorByDateRequireStartUp = new TaskCompartorByDateRequireStartUp();
			Collections.sort(AppMain._listTasksShow,
					taskCompartorByDateRequireStartUp);
			break;
		case AppMain.SORT_TASK_NAME_AZ:
			TaskCompartorByNameUp taskCompartorByNameUp = new TaskCompartorByNameUp();
			Collections.sort(AppMain._listTasksShow, taskCompartorByNameUp);
			break;
		case AppMain.SORT_TASK_NAME_ZA:
			TaskCompartorByNameDown taskCompartorByNameDown = new TaskCompartorByNameDown();
			Collections.sort(AppMain._listTasksShow, taskCompartorByNameDown);
			break;
		// case AppMain.SORT_TASK_WORKER_NAME_AZ:
		// TaskCompartorByWorkerUp taskCompartorByWorkerUp= new
		// TaskCompartorByWorkerUp();
		// Collections.sort(AppMain._tasksListShow,
		// taskCompartorByWorkerUp);
		// break;
		// case AppMain.SORT_TASK_WORKER_NAME_ZA:
		// TaskCompartorByWorkerDown taskCompartorByWorkerDown = new
		// TaskCompartorByWorkerDown();
		// Collections.sort(AppMain._tasksListShow,
		// taskCompartorByWorkerDown);
		// break;

		default:
			break;
		}
		refreshListTasks(false);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.clear();
		MenuInflater menuInflater = getMenuInflater();
		if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_PROJECT)
			menuInflater.inflate(R.menu.menu_option_projects, menu);
		else if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK)
			menuInflater.inflate(R.menu.menu_option_tasks, menu);
		else
			menuInflater.inflate(R.menu.menu_option_tasks_delay, menu);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.menuItemSkype)
		{
			AppMain.startSkype(this);
		}
		else if (item.getItemId() == R.id.menuItemAcount)
		{
			AppMain.showDialogList(this, AppMain.DIALOG_ACCOUNT);
		}
		else
		{
			// project
			if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_PROJECT)
			{
				if (item.getItemId() == R.id.menuItemProjectSort)
				{
					AppMain.showDialogList(this, AppMain.DIALOG_SORT_PROJECT);
				}
				else if (item.getItemId() == R.id.menuItemProjectRefresh)
				{
					if (AppMain._isSMSEnable)
					{
						AppMain.showAlert(this,
								R.string.textMessageSMSAvailableRefresh, false);
					}
					else
					{
						showProgressBar();
						new Thread(new Runnable()
						{
							public void run()
							{
								AppMain._codeResultService = AppMain.doGetProjects(
										MainActivity.this,
										AppMain._user.getUsername());

								synchronizeGPRS();

								AppMain.hideProgressDialog();
							}
						}).start();
					}
				}
			}
			else if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK)
			{/* Task */
				if (item.getItemId() == R.id.menuItemTaskFilter)
				{
					AppMain.showDialogList(this, AppMain.DIALOG_FILTER_TASK);
				}
				else if (item.getItemId() == R.id.menuItemTaskRefresh)
				{
					if (AppMain._isSMSEnable)
					{
						AppMain.showAlert(this,
								R.string.textMessageSMSAvailableRefresh, false);
					}
					else
					{
						showProgressBar();
						new Thread(new Runnable()
						{
							public void run()
							{

								// AppMain._codeResultService =
								// _textProjectName.isShown() ?
								// AppMain.doGetTasksByProjectId(MainActivity.this,
								// AppMain.getCurrentProject().getId()) :
								// AppMain.doGetTasksAll(MainActivity.this);
								if (_textProjectName.getVisibility() != View.VISIBLE)
								{
									AppMain._codeResultService = AppMain.doGetTasksAll(MainActivity.this);
									AppMain.getTasksAll();
								}
								else
								{
									AppMain._codeResultService = AppMain.doGetTasksByProjectId(
											MainActivity.this,
											AppMain.getCurrentProject().getId());
									// AppMain._codeResultService =
									// AppMain.doGetTasksAll(MainActivity.this);
									AppMain.getTasks(AppMain.getCurrentProject().getId());
								}

								synchronizeGPRS();

								AppMain.hideProgressDialog();
							}
						}).start();
					}
				}
				else if (item.getItemId() == R.id.menuItemTaskSort)
				{
					AppMain.showDialogList(this, AppMain.DIALOG_SORT_TASK);
				}

			}
			else
			{/* Task delay */
				if (item.getItemId() == R.id.menuItemTaskDelayFilter)
				{
					AppMain.showDialogList(this,
							AppMain.DIALOG_FILTER_TASK_DELAY);
				}
				else if (item.getItemId() == R.id.menuItemTaskDelayRefresh)
				{
					if (AppMain._isSMSEnable)
					{
						AppMain.showAlert(this,
								R.string.textMessageSMSAvailableRefresh, false);
					}
					else
					{
						showProgressBar();
						new Thread(new Runnable()
						{
							public void run()
							{
								AppMain._codeResultService = AppMain.doGetTasksAll(MainActivity.this);
								AppMain.getTasksDelay();

								synchronizeGPRS();

								AppMain.hideProgressDialog();
							}
						}).start();
					}
				}
				else if (item.getItemId() == R.id.menuItemTaskDelaySort)
				{
					AppMain.showDialogList(this, AppMain.DIALOG_SORT_TASK);
				}

			}
		}
		return true;
	}

	private void refreshListProjects()
	{
		if (AppMain._listProjects == null || AppMain._listProjects.size() == 0)
		{
			// if (!Config.USE_DATABASE) AppMain.doGetProjects(this,
			// AppMain._user.getUsername());
			// else AppMain._listProjects = AppMain._projectSQLite.getAll();
			finish();
		}
		_listViewProjectsAdapter.notifyDataSetChanged();
		_listViewProjects.invalidateViews();
		_textTotalProjects.setText(AppMain._listProjects.size() + " "
				+ getString(R.string.textProjectLowerCase));
	}

	private void refreshListTasks(boolean isFitering)
	{
		_listViewTasksAdapter.notifyDataSetChanged();
		_listViewTasks.invalidateViews();

		_textTotalTasks.setText((_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK_DELAY) ? getTaskDelayTotalString()
				: getTaskTotalString(isFitering));

		// _badgeViewTaskDelay.setText("" + AppMain.getNumberTasksDelay());
		_buttonTabTaskDelay.setText(String.format(
				getString(R.string.textTaskDelay),
				AppMain.getNumberTasksDelay()));
	}

	@Override
	public void onBackPressed()
	{
		AppMain.hideProgressDialog();
		AppMain._isDoneLoading = false;
		if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK_DELAY
				|| _tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK)
		{
			_tabMenu.moveToTab(AppMain.TAB_PROJECT);
			refreshListProjects();
		}
		else
		{
			super.onBackPressed();
		}
	}

	@Override
	protected void onResume()
	{
		super.onResume();

		// refreshListProjects();

		if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK_DELAY)
		{
			AppMain.getTasksDelay();
			refreshListTasks(false);
		}
		else
		{
			if (_textProjectName.getVisibility() != View.VISIBLE)
			{
				AppMain.getTasksAll();
			}
			else
			{
				String currentProjectId = AppMain.getCurrentProject().getId();
				AppMain.getTasks(currentProjectId);
			}
			// AppMain.getTasksAll();
			refreshListTasks(false);
		}

		if (AppMain._numberBackWhenLogout > 0)
		{
			AppMain._numberBackWhenLogout--;
			// finish();
			super.onBackPressed();
		}
	}
}
